package com.woniu.admin.controller;

import com.woniu.admin.entity.SysUserEntity;
import com.woniu.admin.model.SysUserSaveParam;
import com.woniu.admin.service.SysUserService;
import com.woniu.common.req.IdParam;
import com.woniu.common.resp.Result;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author 蜗牛数字化
 * @since 2023-06-18
 */
@Tag(name = "用户")
@RestController
@RequestMapping("/user")
public class SysUserController {

    @Autowired
    SysUserService userService;

    @Operation(summary = "用户列表")
    @PostMapping("/list")
    private Result<List<SysUserEntity>> list() {
        return Result.success(userService.list());
    }

    @Operation(summary = "根据id查找用户")
    @PostMapping("/detail")
    public Result<SysUserEntity> detail(@RequestBody @Validated IdParam param) {
        return Result.success(userService.getById(param.getId()));
    }

    @Operation(summary = "增加修改用户信息")
    @PostMapping("/save")
    public Result save(@RequestBody @Validated SysUserSaveParam param) {
        SysUserEntity entity = new SysUserEntity();
        BeanUtils.copyProperties(param, entity);
        if(entity.getId()==0){
            entity.setId(null);
            entity.setCreateTime(new Date());
            entity.setUpdateTime(new Date());
        }else{
            entity.setUpdateTime(new Date());
        }
        if (userService.save(entity)) {
            return Result.success();
        } else {
            return Result.failure("保存失败，请稍后重试");
        }
    }

    @Operation(summary = "根据id删除用户")
    @PostMapping("/delete")
    public Result delete(@RequestBody @Validated IdParam param) {
        if (userService.removeById(param.getId())) {
            return Result.success();
        } else {
            return Result.failure("删除失败，请稍后重试");
        }
    }
}
